#include "handlemessage.h"
#include <QJsonDocument>
#include <QJsonObject>

handlemessage::handlemessage(MyClientSocket * socket,QObject *parent) : QObject(parent),m_socket(socket)
{
    connect(m_socket,&MyClientSocket::dataRecv,this,&handlemessage::handleRecvDataSlot);
}

void handlemessage::handleLogin(const QByteArray &data)
{
    //1.解析json字符串
    QJsonDocument document = QJsonDocument::fromJson(data);

    //2.将document对象转成json对象
    QJsonObject jsonObj = document.object();

    QString status = jsonObj["status"].toString();
    if(status == "ON_SUCCESS")
    {
        emit loginSignal(true);
    }
    else {
        emit loginSignal(false);
    }
}

void handlemessage::handleRegister(const QByteArray &data)
{
    //1.解析json字符串
    QJsonDocument document = QJsonDocument::fromJson(data);

    //2.将document对象转成json对象
    QJsonObject jsonObj = document.object();

    QString status = jsonObj["status"].toString();
    if(status == "ON_SUCCESS")
    {
        emit registerSignal(true);
    }
    else {
        emit registerSignal(false);
    }
}

void handlemessage::handleMatch(const QByteArray &data)
{
    //1.解析json字符串
    QJsonDocument document = QJsonDocument::fromJson(data);

    //2.将document对象转成json对象
    QJsonObject jsonObj = document.object();

    QString status = jsonObj["status"].toString();
    if(status == "ON_WAIT")
    {
        emit matchSignal("ON_WAIT");
    }
    else
    {
        emit matchSignal(jsonObj["reason"].toString());
    }
}

void handlemessage::handlePlay(const QByteArray &data)
{
    //1.解析json字符串
    QJsonDocument document = QJsonDocument::fromJson(data);

    //2.将document对象转成json对象
    QJsonObject jsonObj = document.object();

    int row = jsonObj["row"].toInt();
    int col = jsonObj["col"].toInt();
    QVector<int> num{row,col};
    emit playSignal(num);
}

void handlemessage::handleBack(const QByteArray &data)
{
    //1.解析json字符串
    QJsonDocument document = QJsonDocument::fromJson(data);

    //2.将document对象转成json对象
    QJsonObject jsonObj = document.object();

    QString status = jsonObj["status"].toString();
    emit backSignal(status);
}

void handlemessage::handleRecvDataSlot(const QByteArray &data)
{
    qDebug() << "data: "<<data<<endl;

    //1.解析json字符串
    QJsonDocument document = QJsonDocument::fromJson(data);

    //2.将document对象转成json对象
    QJsonObject jsonObj = document.object();

    //3.取值
    int type = jsonObj["type"].toInt();
    if(type == LOGIN)
    {
        handleLogin(data);
    }
    else if(type == REGISTER)
    {
        handleRegister(data);
    }
    else if(type == MATCH)
    {
        handleMatch(data);
    }
    else if (type == PLAY)
    {
        handlePlay(data);
    }
    else if(type == BACK)
    {
        handleBack(data);
    }
}
